import {nextTick} from 'vue';

export default {
  getInitFlow() {
    return {
      nodes: [{
        id: 'start',
        type: "start",
      }, {
        id: 'end',
        type: "end",
      }],
      edges: [{
        id: '1',
        source: 'start',
        target: 'end'
      }]
    };
  },
  createId() {
    return 'id_' + Math.random().toString(36).substr(2, 9);
  },
  count: 0,
  createNewNode() {
    return {
      id: this.createId(),
      name: `用户任务${++this.count}`,
      type: 'userTask',
    };
  },
  removeNode(nodeId, graph) {
    let {edges, nodes} = graph.flowModel.value;

    let newEdge = {id: this.createId()}
    edges.forEach(e => {
      if (e.source === nodeId) {
        newEdge.target = e.target
      }
      if (e.target === nodeId) {
        newEdge.source = e.source
      }
    })


    edges = edges.filter(e => e.target !== nodeId && e.source !== nodeId)
    nodes = nodes.filter(n => n.id !== nodeId);
    edges.push(newEdge);
    graph.flowModel.value = {edges, nodes}
    graph.renderFlowModel();
  },
  addNewNodeAfter(nodeId, graph) {
    let newNode = this.createNewNode();
    let {edges, nodes} = graph.flowModel.value;
    nodes.push(newNode);
    edges.forEach(e => {
      if (e.source === nodeId) {
        e.source = newNode.id;
      }
    });
    edges.push({
      id: this.createId(),
      source: nodeId,
      target: newNode.id
    });
    graph.flowModel.value = {edges, nodes}
    graph.renderFlowModel();
  }
};